package com.lanyou.cook.util.gson;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonUtil {
	
	private static final ThreadLocal<Gson> defaultGson = new ThreadLocal<Gson>(){
		protected Gson initialValue() {
			return new Gson();
		};
	};
	
	private static final ThreadLocal<JsonParser> defaultJsonParser = new ThreadLocal<JsonParser>(){
		protected JsonParser initialValue() {
			return new JsonParser();
		};
	};
	
	public static Gson getDefaultGson(){
		return defaultGson.get();
	}
	
	public static JsonParser getDefaultJsonParser(){
		return defaultJsonParser.get();
	}

	public static String getString(JsonObject jsonObject, String key, String defaultValue){
		try{
			return jsonObject.get(key).getAsString();
		} catch (Exception e){
			return defaultValue;
		}
	}
	
	public static boolean getBoolean(JsonObject jsonObject, String key, boolean defaultValue){
		try{
			return jsonObject.get(key).getAsBoolean();
		} catch (Exception e){
			return defaultValue;
		}
	}
	
	public static int getInt(JsonObject jsonObject, String key, int defaultValue){
		try{
			return jsonObject.get(key).getAsInt();
		} catch (Exception e){
			return defaultValue;
		}
	}
	
	public static long getLong(JsonObject jsonObject, String key, long defaultValue){
		try{
			return jsonObject.get(key).getAsLong();
		} catch (Exception e){
			return defaultValue;
		}
	}
	
	public static String getNestedString(JsonObject jsonObject, String propertyPathStr, String defaultValue){
		try{
			String[] propertyPath = StringUtils.split(propertyPathStr, '.');
			
			JsonElement jo = jsonObject.get(propertyPath[0]);
			for(int i = 1; i < propertyPath.length; i += 1){
				jo = jo.getAsJsonObject().get(propertyPath[i]);
			}
			return jo.getAsString();
		} catch (Exception e){
			return defaultValue;
		}
	}
}
